<?php
/**
 *
 * @author: jing.chen
 * @date: 2018/3/19 18:58
 */
include_once dirname(dirname(__FILE__)) . "/common.php";
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_core.m_file");

class m_split_file
{

    public $dir;

    public $type;

    public $line;

    public $bit;

    public $name;

    public $is_delete;

    public $file_type;

    public $store_dir;

    public function __construct($dir = null, $file_type = null, $store_dir = null, $path = null, $type = 1, $line = 1000, $name = "test", $bit = "1m", $delete = 1)
    {
        $this->dir = $dir; // 切割文件路径
        $this->file_type = ($file_type) ? $file_type : substr(strrchr($dir, '.'), 1); // 文件后缀名
        $this->store_dir = $store_dir; // 切割完成后的文件存放路劲
        $this->type = $type; // 切割文件模式 1按照行数切割 2按照字节大小切割 默认1
        $this->line = $line; // 切割行数 默认1000行
        $this->bit = $bit; // 切割字节大小 默认1m
        $this->name = $name; // 切割后文件名称 默认test
        $this->is_delete = $delete; // 切割完成后 是否删除源文件 1删除 0不删除 默认1
        $this->path = $path; // 切割完成后文件的路径
    }

    public function run()
    {
        $dir = $this->dir;
        $name = $this->name;
        $file_type = $this->file_type;
        $store_dir = $this->store_dir;
        $path = $this->path;
        if(!isset($dir) || empty($dir) || !file_exists($dir))
        {
            return m_config::return_data(1, '切割文件为空或不存在');
        }
        if (! isset($path) || empty($path)) 
        {
            return m_config::return_data(1, '切割后的文件路径为空');
        }
        if ($this->type == 1) 
        {
            $type = "-l";
            $num = $this->line;
        } 
        else 
        {
            $type = "-b";
            $num = $this->bit;
        }
        $linux_exec = "cd {$this->store_dir}/ && split " . $type . " " . $num . " " . $dir . " " . $name;
        $status = 1;
        $log = '';
        exec($linux_exec, $log, $status);
        if($status)
        {
            return m_config::return_data(1, '切割失败'.$linux_exec);
        }
        // 删除源文件
        if (! empty($this->is_delete)) 
        {
            unlink($dir);
        }
        
        
        if(strlen($file_type) <1)
        {
            return m_config::return_data(0, '切割成功，无后缀名');
        }
        $arr_file = m_file::get_files($this->store_dir);
        if (empty($arr_file) || ! is_array($arr_file))
        {
            return m_config::return_data(1, '没生成任何文件');
        }
        foreach ($arr_file as $value)
        {
            exec("rename {$value} {$value}.{$file_type} {$value}", $log, $status);
            if($status)
            {
                return m_config::return_data(1, '修改文件后缀名失败');
            }
        }
        return m_config::return_data(0, 'OK');
    }
}